/*
 * Filename:    AttendantProviderServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月24日
 */
package com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.base.dto.BaseDTO;
import com.paic.mhis.common.base.dto.PaginatedQueryDTO;
import com.paic.mhis.common.base.dto.PaginationDTO;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.BusinessServiceUtil;
import com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.AttendantProviderService;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.AttendantChangeRecordDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.AttendantInfoDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.ChangeRecordDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.ContactDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.HospitalProviderOrgDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.integration.dao.AttendantInfoDao;
import com.paic.mhis.hcpms.agreement.healthcareprovider.integration.dao.HospitalProviderOrgDao;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.Constants;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.HealthCareConstants;
import com.paic.mhis.hcpms.agreement.healthcareprovider.validator.ProviderValidator;
import com.paic.pafa.app.biz.service.BaseService;

/**
 * 
 * @author EX-FENGHE001
 * 
 */
@Service("attendantProviderService")
public class AttendantProviderServiceImpl extends BaseService implements
		AttendantProviderService {

	private static final Logger LOG = Logger
			.getLogger(AttendantProviderServiceImpl.class);

	@Autowired
	private HospitalProviderOrgDao hospitalProviderOrgDao;

	@Autowired
	private AttendantInfoDao attendantInfoDao;

	@Autowired
	private CommonDAO commonDAO;

	private ProviderValidator providerValidator;

	@Override
	public Map<String, Object> findHospitalProviderOrgList(
			JSONObject transferJson) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String userName = transferJson.getString("userName");
			List<Map<String, String>> userTypeList = this.getUserType(userName);
			String userType = "";
			String orgCode = "";
			if (null != userTypeList) {
				for (int i = 0; i < userTypeList.size(); i++) {
					Map<String, String> tempMap = userTypeList.get(i);
					userType = (String) tempMap.get("accountType");
					orgCode = orgCode + "'" + (String) tempMap.get("orgCode")
							+ "',";
				}
			}
			// 医院类型账户
			if (HealthCareConstants.USER_HOSPITAL.equals(userType)) {
				orgCode = orgCode.substring(0, orgCode.length() - 1);
				transferJson.put("orgCode", orgCode);
			}
			PaginationDTO pdto = new PaginationDTO();
			pdto.setQueryParams(JSONObject
					.toJavaObject(transferJson, Map.class));
			int page = Integer.parseInt(transferJson.getString("page"));
			int pageSize = Integer.parseInt(transferJson.getString("pageSize"));
			pdto.setStart((page - 1) * pageSize);
			pdto.setEnd(page * pageSize);
			pdto.setDoCount(true);
			pdto.setQueryAll(false);
			pdto.setLimit(pageSize);
			resultMap = commonDAO.queryPage(
					"hospitalProviderOrgDao.findHospitalProviderOrgList", pdto);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> findHospitalProviderOrgDetail(
			JSONObject transferJson) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> result = null;
		List<Map<String, Object>> contactList = null;
		try {
			HospitalProviderOrgDTO dto = JSONObject.toJavaObject(transferJson,
					HospitalProviderOrgDTO.class);
			dto = hospitalProviderOrgDao.findHospitalProviderOrgDetail(dto);
			String providerCode = dto.getProviderCode();
			resultMap.put("result", dto);
			Map<String, Object> queryParm = new HashMap<String, Object>();
			List<String> contactTypes = new ArrayList<String>();
			contactTypes.add("1");
			contactTypes.add("2");
			queryParm.put("providerId", providerCode);
			// 联系人信息
			result = (List<Map<String, Object>>) commonDAO.query(
					"healthcare.queryContactList", queryParm);
			resultMap.put("contact", result);
			queryParm.put("contactType", contactTypes);
			// 医保负责人信息
			contactList = (List) commonDAO.query("healthcare.queryContactList",
					queryParm);
			for (int i = 0; i < contactList.size(); i++) {
				Map<String, Object> tempMap = (Map<String, Object>) contactList
						.get(i);
				String contactType = (String) tempMap.get("contactype");
				if ("1".equals(contactType)) {
					resultMap.put("responsible", tempMap);
				} else {
					resultMap.put("contacts", tempMap);
				}
			}
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Transactional
	@Override
	public Map<String, Object> saveHospitalProviderOrg(JSONObject transferJson) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			providerValidator = (ProviderValidator) context
					.getBean("providerValidator");
			Map<Object, Object> fieldMap = JSONObject.toJavaObject(
					transferJson, Map.class);
			Map<Object, Object> validateResult = providerValidator
					.validate(fieldMap);
			if (validateResult == null) {
				putResultMap(transferJson, resultMap);
			} else {
				BusinessServiceUtil.generateExceptionResult(resultMap,
						Constants.STATE_KEY,
						Constants.FAILED_VALIDATE_STATE_VALUE,
						Constants.VALIDATE_ERRORS_KEY, BusinessServiceUtil
								.getValidateFailedMsg(validateResult));
			}

		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	private void putResultMap(JSONObject transferJson,
			Map<String, Object> resultMap) {
		String providerId = transferJson.getString("providerId");
		String createBy = (String) transferJson.get("createBy");
		String updateBy = (String) transferJson.get("updateBy");
		if ("".equals(providerId) || null == providerId) {
			providerId = commonDAO.getUUID();
		}
		HospitalProviderOrgDTO dto = JSONObject.toJavaObject(transferJson,
				HospitalProviderOrgDTO.class);
		String providerCode = dto.getProviderCode();
		JSONArray contact = (JSONArray) transferJson.remove("contactList");
		JSONArray ja = (JSONArray) transferJson.remove("updateList");
		JSONObject relationDetail1 = (JSONObject) transferJson
				.remove("relationDetail1");
		JSONObject relationDetail2 = (JSONObject) transferJson
				.remove("relationDetail2");
		addContact(providerCode, relationDetail1, relationDetail2, createBy,
				updateBy);

		if (dto.getProviderId() != null
				&& !"".equals(dto.getProviderId().trim())) {
			hospitalProviderOrgDao.updateHospitalProviderOrg(dto);
			for (int i = 0; i < ja.size(); i++) {
				JSONObject tempJb = ja.getJSONObject(i);
				tempJb.put("createdBy", createBy);
				tempJb.put("updatedBy", updateBy);
				addChangeRecord(tempJb);
			}
			resultMap.put(Constants.MSG_KEY, Constants.UPDATE_SUCCESS);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
		} else {
			// 保存联系人
			if (!contact.isEmpty() && contact.size() != 0) {
				for (int i = 0; i < contact.size(); i++) {
					ContactDTO contactDTO = null;
					contactDTO = JSONObject.toJavaObject(
							contact.getJSONObject(i), ContactDTO.class);
					contactDTO.setDepartment(contactDTO.getDepartmentNo());
					contactDTO.setProviderid(providerCode);
					contactDTO.setCreateby(createBy);
					contactDTO.setUpdateby(updateBy);
					commonDAO.insert("healthcare.addContact", contactDTO);
				}
			}

			resultMap.put(Constants.MSG_KEY, Constants.INSERT_SUCCESS);
			resultMap.put("providerId", providerId);
			dto.setProviderId(providerId);
			hospitalProviderOrgDao.addHospitalProviderOrg(dto);
			Map<String, String> queryMap = new HashMap<String, String>();
			queryMap.put("region", dto.getRegionCode());
			queryMap.put("type", "1");
			commonDAO.update("healthcare.updateRuleCode", queryMap);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
		}

	}

	private void addContact(String providerId, JSONObject relationDetail1,
			JSONObject relationDetail2, String createBy, String updateBy) {
		// 获取医保负责人id
		try {
			Map<String, String> parm = new HashMap<String, String>();
			parm.put("contactType", "1");
			parm.put("providerId", providerId);
			String id = (String) commonDAO.get(
					"hospitalProviderOrgDao.getContactId", parm);
			ContactDTO contactDTO = null;
			contactDTO = JSONObject.toJavaObject(relationDetail1,
					ContactDTO.class);
			contactDTO.setContactype("1");
			contactDTO.setProviderid(providerId);
			contactDTO.setCreateby(createBy);
			contactDTO.setUpdateby(updateBy);
			if ("".equals(id) || null == id) {
				commonDAO.insert("healthcare.addContact", contactDTO);
			} else {
				contactDTO.setId(id);
				commonDAO.update("healthcare.updateContact", contactDTO);
			}
			// 获取医保联系人id
			parm = new HashMap<String, String>();
			parm.put("contactType", "2");
			parm.put("providerId", providerId);
			id = (String) commonDAO.get("hospitalProviderOrgDao.getContactId",
					parm);
			contactDTO = null;
			contactDTO = JSONObject.toJavaObject(relationDetail2,
					ContactDTO.class);
			contactDTO.setContactype("2");
			contactDTO.setProviderid(providerId);
			contactDTO.setCreateby(createBy);
			contactDTO.setUpdateby(updateBy);
			if ("".equals(id) || null == id) {
				commonDAO.insert("healthcare.addContact", contactDTO);
			} else {
				contactDTO.setId(id);
				commonDAO.update("healthcare.updateContact", contactDTO);
			}
		} catch (Exception e) {
			LOG.error(e);
		}
	}

	@Override
	public Map<String, Object> deleteHospitalProviderOrg(JSONObject transferJson) {
		Map<String, String> parms = new HashMap<String, String>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String id = transferJson.getString("ids");
			String ids = "";
			if (null != id && !"".equals(id)) {
				ids = id.substring(0, id.length() - 1);
			}
			parms.put("ids", ids);
			parms.put("updatedBy", transferJson.getString("updatedBy"));
			commonDAO.update(
					"hospitalProviderOrgDao.deleteHospitalProviderOrg", parms);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.DELETE_SUCCESS);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> findAttendantInfoList(int pageSize, int page,
			Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String userName = (String) params.get("userName");
			List<Map<String, String>> userTypeList = this.getUserType(userName);
			String userType = "";
			String orgCode = "";
			if (null != userTypeList) {
				for (int i = 0; i < userTypeList.size(); i++) {
					Map<String, String> tempMap = userTypeList.get(i);
					userType = (String) tempMap.get("accountType");
					orgCode = "'" + (String) tempMap.get("orgCode") + "',";
				}
			}
			// 医院类型账户
			if (HealthCareConstants.USER_HOSPITAL.equals(userType)) {
				orgCode = orgCode.substring(0, orgCode.length() - 1);
				params.put("orgCode", orgCode);
			}
			PaginatedQueryDTO dto = new PaginatedQueryDTO();
			dto.setStart(pageSize);
			dto.setLimit(page);
			dto.setParam(params);
			resultMap = commonDAO.queryPage(
					"attendantInfoDao.findAttendantInfoList", dto);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> findAttendantDetail(JSONObject transferJson) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			AttendantInfoDTO dto = JSONObject.toJavaObject(transferJson,
					AttendantInfoDTO.class);
			resultMap.put("result", attendantInfoDao.findAttendantDetail(dto));
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> findHistoryChangeRecord(JSONObject transferJson) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			AttendantChangeRecordDTO dto = JSONObject.toJavaObject(
					transferJson, AttendantChangeRecordDTO.class);
			resultMap.put("result",
					attendantInfoDao.findHistoryChangeRecord(dto));
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Override
	public int queryContactCount(Map<String, Object> map) {
		int count = 0;
		try {
			count = (int) commonDAO.count(
					"attendantInfoDao.findAttendantInfoCount", map);
		} catch (Exception e) {
			LOG.error(e);
		}
		return count;
	}

	@Override
	public List getInsuranceList(int start, int limit, Map<String, Object> param) {
		PaginatedQueryDTO dto = new PaginatedQueryDTO();
		dto.setStart(start);
		dto.setLimit(limit);
		dto.setParam(param);
		return commonDAO.query("attendantInfoDao.findAttendantInfoList2", dto);
	}

	@Override
	public Map<String, Object> addChangeRecord(JSONObject transferJson) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			ChangeRecordDTO changeRecordDTO = null;
			changeRecordDTO = JSONObject.toJavaObject(transferJson,
					ChangeRecordDTO.class);
			String codeType = changeRecordDTO.getCodeType();
			String changeBefore = changeRecordDTO.getChangeBefore();
			String changeAfter = changeRecordDTO.getChangeAfter();
			if (null != codeType && "cityDep".equals(codeType)
					|| "provincialDep".equals(codeType)) {
				List<BaseDTO> list;
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				// 根据前端传入的编码类型编号，在配置文件中找到对应的编码类型；
				paramsMap.put("codeType", codeType);
				paramsMap.put("codeNo", changeBefore);
				list = commonDAO.query("base.codeList", paramsMap);
				Map<String, Object> codeMap = (Map<String, Object>) list.get(0);
				changeBefore = (String) codeMap.get("codename");
				changeRecordDTO.setChangeBefore(changeBefore);
				paramsMap.put("codeNo", changeAfter);
				list = commonDAO.query("base.codeList", paramsMap);
				codeMap = (Map<String, Object>) list.get(0);
				changeAfter = (String) codeMap.get("codename");
				changeRecordDTO.setChangeAfter(changeAfter);
			} else if (null != codeType
					&& "qualification_level".equals(codeType)) {
				List<BaseDTO> list;
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				// 根据前端传入的编码类型编号，在配置文件中找到对应的编码类型；
				paramsMap.put("codeType", codeType);
				paramsMap.put("codeNo", changeBefore);
				list = commonDAO.query("base.codeListTypes", paramsMap);
				Map<String, Object> codeMap = (Map<String, Object>) list.get(0);
				changeBefore = (String) codeMap.get("codename");
				changeRecordDTO.setChangeBefore(changeBefore);
				paramsMap.put("codeNo", changeAfter);
				list = commonDAO.query("base.codeListTypes", paramsMap);
				codeMap = (Map<String, Object>) list.get(0);
				changeAfter = (String) codeMap.get("codename");
				changeRecordDTO.setChangeAfter(changeAfter);
			} else if (null != codeType && "serviceStus".equals(codeType)) {
				// 根据前端传入的编码类型编号，在配置文件中找到对应的编码类型；
				changeBefore = "0".equals(changeBefore) ? "有效" : "1"
						.equals(changeBefore) ? "无效" : "无";
				changeRecordDTO.setChangeBefore(changeBefore);
				changeAfter = "0".equals(changeAfter) ? "有效" : "1"
						.equals(changeAfter) ? "无效" : "无";
				changeRecordDTO.setChangeAfter(changeAfter);
			}
			commonDAO.insert("attendantInfoDao.addChangeRecord",
					changeRecordDTO);
			result.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			result.put(Constants.MSG_KEY, Constants.INSERT_SUCCESS);
		} catch (Exception e) {
			LOG.error(e);
		}
		return result;
	}

	@Override
	public Map<String, Object> findChangeRecord(String providerid) {
		AttendantChangeRecordDTO ard = new AttendantChangeRecordDTO();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			ard.setRelationId(providerid);
			ard.setChangeType("0");
			List list = commonDAO.query(
					"attendantInfoDao.findHistoryChangeRecord", ard);
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SELECT_SUCCESS);
			resultMap.put(Constants.SUCCESS_RESULT_KEY, list);
		} catch (Exception e) {
			LOG.error(e);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> getProviderCode(JSONObject transferJson) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, String> queryMap = new HashMap<String, String>();
		queryMap.put("region", transferJson.getString("region"));
		queryMap.put("type", "1");
		String code = (String) commonDAO.get("healthcare.getRuleCode2",
				queryMap);
		resultMap.put("providerCode", code);

		return resultMap;
	}

	@Override
	public List<Map<String, String>> getUserType(String username) {

		return (List<Map<String, String>>) commonDAO.query("getUserType",
				username);
	}
}
